<?php

namespace app\admin\model\sum\trade;

use app\admin\model\oil\order\RefundLog;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
use app\admin\model\sum\user\User;
use app\admin\model\sum\Pay as PayModel;

class Order extends Model
{
    use SoftDelete;

    protected $name = 'sum_trade_order';

    protected $deleteTime = 'deletetime';

    protected $type = [
        'ext' => 'json',
        'paid_time' => 'timestamp',
    ];

    // 追加属性
    protected $append = [
        'type_text',
        'status_text',
        'platform_text',
    ];


    // 订单状态
    const STATUS_CLOSED = 'closed';
    const STATUS_CANCEL = 'cancel';
    const STATUS_UNPAID = 'unpaid';
    const STATUS_PAID = 'paid';
    const STATUS_COMPLETED = 'completed';
    const STATUS_REFUND = 'refund';

    public function statusList()
    {
        return [
            'closed' => '交易关闭',
            'cancel' => '已取消',
            'unpaid' => '未支付',
            'paid' => '已支付',
            'completed' => '已完成',
            'refund' => '已退款'
        ];
    }


    /**
     * 订单列表状态搜索
     */
    public function searchStatusList()
    {
        return [
            'unpaid' => '待付款',
            'paid' => '已支付',      // 包括刚支付的，以及已完成的所有付过款的订单
            'completed' => '已完成',
            'cancel' => '已取消',
            'closed' => '交易关闭',
            'refund' => '已退款',
        ];
    }


    public function typeList()
    {
        return [
            'recharge' => '充值订单',
        ];
    }

    /**
     * 通用类型获取器
     *
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getTypeTextAttr($value, $data)
    {
        $value = $value ?: ($data['type'] ?? null);

        $list = $this->typeList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    /**
     * 通用状态获取器
     *
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');

        $list = $this->statusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function platformList()
    {
        return [
            'H5' => 'H5',
            'WechatOfficialAccount' => '微信公众号',
            'WechatMiniProgram' => '微信小程序',
            'App' => 'App',
        ];
    }


    public function getPlatformTextAttr($value, $data)
    {
        $value = $value ?: ($data['platform'] ?? null);

        $list = $this->platformList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    /**
     * 已支付订单，支付类型
     *
     * @param string $value
     * @param array $data
     * @return void
     */
    public function getPayTypeAttr($value, $data)
    {
        $status = $data['status'] ?? '';
        $payTypes = [];
        if (in_array($status, [self::STATUS_PAID, self::STATUS_COMPLETED])) {
            $payTypes = PayModel::typeTradeOrder()->where('table_id', $data['id'])->where('status', '<>', PayModel::PAY_STATUS_UNPAID)->group('pay_type')->column('pay_type');
        }

        return $payTypes[0] ?? '';
    }


    /**
     * 已支付订单，支付类型文字
     *
     * @param string $value
     * @param array $data
     * @return void
     */
    public function getPayTypeTextAttr($value, $data)
    {
        $pay_types = $this->pay_type;
        $list = (new PayModel)->payTypeList();

        return isset($list[$pay_types]) ? $list[$pay_types] : '';
    }



    // 已关闭
    public function scopeClosed($query)
    {
        return $query->where('status', Order::STATUS_CLOSED);
    }

    // 已取消
    public function scopeCancel($query)
    {
        return $query->where('status', Order::STATUS_CANCEL);
    }

    // 未支付
    public function scopeUnpaid($query)
    {
        return $query->where('status', Order::STATUS_UNPAID);
    }

    // 已支付
    public function scopePaid($query)
    {
        return $query->whereIn('status', [Order::STATUS_PAID, Order::STATUS_COMPLETED,Order::STATUS_REFUND]);
    }

    // 已完成
    public function scopeCompleted($query)
    {
        return $query->where('status', Order::STATUS_COMPLETED);
    }


    public function scopeRecharge($query)
    {
        return $query->where('type', 'recharge');
    }



    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function pays()
    {
        return $this->hasMany(PayModel::class, 'table_id', 'id')->typeTradeOrder();
    }

    /**
     * 支付完成回调
     * @param $order
     * @param $notify
     */
    public function paymentProcess($order, $notify)
    {
        $order->status = Order::STATUS_PAID;
        $order->paid_time = time();
        $order->save();

        $user = User::where('id', $order->user_id)->find();
        User::where('id', $order->user_id)->setInc('re_times');
        // 支付成功后续使用异步队列处理
//        \think\Queue::push('\addons\shopro\job\OrderPayed@payed', ['order' => $order, 'user' => $user], 'shopro-high');

        // 充值到余额
        User::money($order->order_amount, $order->user_id, 'recharge', $order->id);
        return $order;
    }

    // 开始退款
    public static function startRefund($order, $refund_money, $user = null, $remark = '') {
        // 订单退款前
        $data = ['order' => $order];
        \app\admin\model\sum\trade\Order::refund($order, $refund_money, $remark);
    }

    // 退款
    public static function refund($order, $refund_money, $remark = '')
    {
        $pay_type='wechat';//只有微信支付

        $remark='';//不让显示退款原因
        // 生成退款单
        $refundLog = new RefundLog();
        $refundLog->order_sn = $order->order_sn;
        $refundLog->refund_sn = RefundLog::getSn($order->user_id,"TOR");
        $refundLog->pay_fee = $order->pay_fee;
        $refundLog->refund_fee = $refund_money;
        $refundLog->pay_type = $pay_type;
        $refundLog->table_name = 'sum_trade_order';
        $refundLog->table_id = $order->id;
        $refundLog->save();



        if ($pay_type == 'wechat' || $pay_type == 'alipay') {
            // 微信|支付宝退款
            $payOrder=Db::name('sum_pay_order')->where('table_name','sum_trade_order')->where('table_id',$order['id'])->where('ispay',1)->find();
            // 退款数据
            $order_data = [
                'out_trade_no' => $payOrder['out_trade_no']
            ];

            if ($pay_type == 'wechat') {
                $total_fee = $order->pay_fee * 100;
                $refund_fee = $refund_money * 100;
                $order_data = array_merge($order_data, [
                    'out_refund_no' => $refundLog->refund_sn,
                    'amount'=>[
                        'refund' => $refund_fee,
                        'total' => $total_fee,
                        'currency' => 'CNY',
                    ],
//                    'reason' => $remark,
                ]);
            } else {
                $order_data = array_merge($order_data, [
                    'out_request_no' => $refundLog->refund_sn,
                    'refund_amount' => $refund_money,
                ]);
            }

            $notify_url = request()->domain() . '/addons/sum/pay/notifyr/payment/' . $pay_type . '/platform/' . $order->platform;

            $pay = new \addons\sum\library\PayService($pay_type, $order->platform, $notify_url);
            $result = $pay->refund($order_data);

            \think\Log::write('refund-result' . json_encode($result));


            if ($pay_type == 'wechat') {
                // 微信通知回调 pay->notifyr
//                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                if (!$result['code']) {
                    return true;
                } else {
                    throw new \Exception($result['message']);
                }
            } else {
                // 支付宝通知回调 pay->notifyx
                if ($result['code'] == "10000") {
                    return true;
                } else {
                    throw new \Exception($result['msg']);
                }
            }
        } else if ($pay_type == 'wallet') {
            // 余额退款
            if ($refund_money != 0) {
                \addons\sum\model\User::money($refund_money, $order->user_id, 'wallet_refund', $order->id, '', [
                    'order_id' => $order->id,
                    'order_sn' => $order->order_sn,
                ]);
            }

            self::refundFinish($order, $refundLog);

            return true;
        } else if ($pay_type == 'score') {
            // 积分退款，暂不支持积分退款
            return false;
        }
    }
    public static function refundFinish($order, $refundLog)
    {
        // 退款完成
        $refundLog->status = 1;
        $refundLog->save();

        // 退款完成
        $order->status = 'refund';    // 退款完成
        $order->refund_fee = $refundLog->refund_fee;    // 退款金额
        $order->refund_time = time();    // 退款完成时间
//        $order->ext = json_encode($order->setExt($order, ['refund_time' => time()]));      // 退款完成时间
        $order->save();
    }
}
